package com.youcheng.configcenter.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author sunhongmin
 * @date 2022/10/21 17:49
 * @description
 */
public class DataAccessBase {

    private final String DRIVER_CLASS_NAME;
    private final String JDBC_URL;
    private final String JDBC_USERNAME;
    private final String JDBC_PASSW;

    private Connection connection;


    public DataAccessBase(String DRIVER_CLASS_NAME, String JDBC_URL, String JDBC_USERNAME, String JDBC_PASSW) {
        this.DRIVER_CLASS_NAME = DRIVER_CLASS_NAME;
        this.JDBC_URL = JDBC_URL;
        this.JDBC_USERNAME = JDBC_USERNAME;
        this.JDBC_PASSW = JDBC_PASSW;
    }


    public PreparedStatement getSqlPrepareStatement(String sql, Object[] columnNames) throws SQLException, ClassNotFoundException {
        Class.forName(DRIVER_CLASS_NAME);
        this.connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSW);
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < columnNames.length; i++) {
            preparedStatement.setObject(i + 1, columnNames[i]);
        }
        return preparedStatement;
    }

    /**
     * 关闭连接
     */
    public void closeConnection(){
        if(Objects.nonNull(connection)){
            try {
                connection.close();
            } catch (SQLException ignored) {
            }
        }
    }



}
